import React, { useState } from 'react';
import { Card, Input, Button, Select, Spin, message, Tabs } from 'antd';
import { JsonViewer } from '@textea/json-viewer';
import axios from 'axios';

const { TextArea } = Input;
const { Option } = Select;
const { TabPane } = Tabs;

const ApiTest = () => {
  const [method, setMethod] = useState('get');
  const [requestJson, setRequestJson] = useState('{\n  "User": {\n    "id": 38710\n  }\n}');
  const [loading, setLoading] = useState(false);
  const [response, setResponse] = useState(null);
  const [error, setError] = useState(null);

  // 示例请求
  const examples = {
    'get': [
      {
        name: '获取单个用户',
        json: '{\n  "User": {\n    "id": 38710\n  }\n}'
      },
      {
        name: '获取用户列表',
        json: '{\n  "[]": {\n    "count": 3,\n    "User": {\n      "@column": "id,name"\n    }\n  }\n}'
      },
      {
        name: '获取动态及发布者',
        json: '{\n  "Moment": {\n    "id": 12\n  },\n  "User": {\n    "id@": "/Moment/userId"\n  }\n}'
      },
      {
        name: '获取类似朋友圈的动态列表',
        json: '{\n  "[]": {\n    "page": 0,\n    "count": 2,\n    "Moment": {},\n    "User": {\n      "id@": "/Moment/userId",\n      "@column": "id,name,head"\n    },\n    "Comment[]": {\n      "count": 2,\n      "Comment": {\n        "momentId@": "[]/Moment/id"\n      }\n    }\n  }\n}'
      }
    ],
    'head': [
      {
        name: '获取用户数量',
        json: '{\n  "User": {}\n}'
      },
      {
        name: '获取特定用户发布的动态数量',
        json: '{\n  "Moment": {\n    "userId": 38710\n  }\n}'
      }
    ],
    'post': [
      {
        name: '新增评论',
        json: '{\n  "Comment": {\n    "momentId": 12,\n    "content": "APIJSON is the real-time coding-free, powerful and secure ORM"\n  },\n  "tag": "Comment"\n}'
      }
    ],
    'put': [
      {
        name: '修改动态内容',
        json: '{\n  "Moment": {\n    "id": 12,\n    "content": "APIJSON is the real-time coding-free, powerful and secure ORM"\n  },\n  "tag": "Moment"\n}'
      }
    ],
    'delete': [
      {
        name: '删除评论',
        json: '{\n  "Comment": {\n    "id": 1\n  },\n  "tag": "Comment"\n}'
      }
    ]
  };

  const handleMethodChange = (value) => {
    setMethod(value);
    if (examples[value] && examples[value].length > 0) {
      setRequestJson(examples[value][0].json);
    }
  };

  const handleExampleChange = (json) => {
    setRequestJson(json);
  };

  const handleSendRequest = async () => {
    setLoading(true);
    setError(null);
    
    try {
      // 解析JSON
      const jsonData = JSON.parse(requestJson);
      
      // 发送请求
      const response = await axios.post(`/${method}`, jsonData);
      setResponse(response.data);
    } catch (error) {
      console.error('请求失败:', error);
      if (error.response) {
        setError(`请求失败: ${error.response.status} ${error.response.statusText}`);
      } else if (error.message.includes('JSON')) {
        setError(`JSON解析错误: ${error.message}`);
      } else {
        setError(`请求错误: ${error.message}`);
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card title="APIJSON API 测试">
      <div style={{ marginBottom: 16 }}>
        <Select
          value={method}
          onChange={handleMethodChange}
          style={{ width: 120, marginRight: 16 }}
        >
          <Option value="get">GET</Option>
          <Option value="head">HEAD</Option>
          <Option value="gets">GETS</Option>
          <Option value="heads">HEADS</Option>
          <Option value="post">POST</Option>
          <Option value="put">PUT</Option>
          <Option value="delete">DELETE</Option>
        </Select>
        
        <Select
          style={{ width: 200 }}
          placeholder="选择示例请求"
          onChange={(_, option) => handleExampleChange(option.json)}
        >
          {examples[method] && examples[method].map((example, index) => (
            <Option key={index} json={example.json} value={index}>
              {example.name}
            </Option>
          ))}
        </Select>
      </div>

      <Tabs defaultActiveKey="request">
        <TabPane tab="请求" key="request">
          <TextArea
            value={requestJson}
            onChange={(e) => setRequestJson(e.target.value)}
            autoSize={{ minRows: 10, maxRows: 20 }}
            style={{ marginBottom: 16, fontFamily: 'monospace' }}
          />
          
          <Button 
            type="primary" 
            onClick={handleSendRequest} 
            loading={loading}
          >
            发送请求
          </Button>
        </TabPane>
        
        <TabPane tab="响应" key="response">
          <Spin spinning={loading}>
            {error ? (
              <div style={{ color: 'red', marginBottom: 16 }}>{error}</div>
            ) : response ? (
              <JsonViewer
                value={response}
                rootName={false}
                displayDataTypes={false}
                displaySize={false}
                defaultInspectDepth={1}
                theme="light"
                style={{ marginTop: 16 }}
              />
            ) : (
              <div style={{ marginTop: 16 }}>发送请求后查看响应...</div>
            )}
          </Spin>
        </TabPane>
      </Tabs>
    </Card>
  );
};

export default ApiTest; 